import React, {Component} from 'react'
import {browserHistory} from 'react-router';
import cookie from 'react-cookie';
// import Modal from 'react-modal';
import {Modal} from 'antd'
import $ from 'jquery'

import styles from './index.scss';

export default class LoginComponent extends Component {

    constructor(props) {
        super(props);
        this.state = {
            userName: "",
            userPassword: "",
            isRemember: false,
            modalIsOpen: false,
            modalMessage: '',
            loginLoading: '登录'
        };
    }
    componentDidMount() {
        // let userId = cookie.load('userId'); let userPwd = cookie.load('userPwd'); if
        // (userId && userPwd){    //  window.location.hash = '/main'
        // browserHistory.push('/main'); }
    }
    //alertModal
    openModal = (msg) => {
        this.setState({modalIsOpen: true, modalMessage: msg})
    }
    afterOpenModal = () => {
        // references are now sync'd and can be accessed.
        this.refs.subtitle.style.color = '#666';
        this.refs.subtitle.style.margin = '20px 100px 20px 0px';
        this.refs.subtitle.style.fontSize = '16px';
    }
    closeModal = () => {
        this.setState({modalIsOpen: false, modalMessage: ''});
    }

    changeUsername = (e) => {
        let uname = e.target.value;
        this.setState({userName: uname});
    }
    changePassword = (e) => {
        let upwd = e.target.value;
        this.setState({userPassword: upwd})
    }
    //是否记住密码
    handleCheckbox = (e) => {
        let isChecked = e.target.checked;
        if (isChecked) {
            this.setState({isRemember: true})
        } else {
            this.setState({isRemember: false})
        }
    }
    isHandleClick = (e) => {
        if(e.keyCode == 13){
            this.handleClick();
        }
    }

    
    handleClick = () => {
        //提交表单 成功后进行跳转
        if (this.state.userName === "" || this.state.userName === null) {
            this.openModal('账号不能为空');
        } else if (this.state.userPassword === "" || this.state.userPassword === null) {
            this.openModal('密码不能为空');
        } else {

            if (this.state.isRemember === true) { //是否记住密码，若记住，则保存至localstorage，反之，清除
                // let loginData = {}; loginData.userName = this.state.userName;
                // loginData.userPassword = this.state.userPassword; let d=new Date();
                // d.setDate(d.getDate()+30);
                //
                // cookie.save('userId', loginData.userName, { path: '/', expires:d });
                // cookie.save('userPwd', loginData.userPassword, { path: '/', expires:d });

            } else {
                //Data.localRemoveItem("jiaj-loginStatus");

            }
            //this.state.userName   userPassword
            this.setState({
                loginLoading: '登录中'
            })
            $.ajax({
                    url: '/base/auth/login',
                    type: 'post',
                    dataType: 'json',
                    data: {
                        username: this.state.userName,
                        password: this.state.userPassword
                    }
                })
                .done(function (data, status, xhr) {
                    // console.log("----------",  JSON.stringify(data, null, 4));
                    if (data.code == "1") {
                        this.setState({
                            loginLoading: '登录'
                        })
                        browserHistory.push('/main');
                    } else {
                        console.log("失败：", data.msg);
                        this.setState({
                            loginLoading: '登录'
                        })
                        // alert("失败："+ data.msg);
                        this.openModal(data.msg);
                    }
                }.bind(this));
        }
    }
    render() {

        const modelStyles = {
            overlay: {
                position: 'fixed',
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                backgroundColor: 'rgba(0, 0, 0, 0.3)'
            },
            content: {
                top: '50%',
                left: '50%',
                right: 'auto',
                bottom: 'auto',
                marginRight: '-50%',
                transform: 'translate(-50%, -150%)',
                backgroundColor: '#f1f1f1'
            }
        };
        const modalBtnStyle = {
            float: 'right',
            marginTop: '10px',
            borderRadius: '4px',
            cursor: 'pointer',
            border: 'none',
            padding: '5px 10px',
            outline: 'none',
            background: '#1e99dd',
            color: '#ffffff'
        }
        let modalMessage = this.state.modalMessage;
        return (
            <div className={styles.loginBox}>
                <form action="" className={styles.horizontal} onKeyDown={this.isHandleClick}>
                    <div className={styles.loginTop}>
                        <span className={styles.changeLanguage}>语言切换</span>
                    </div>
                    <div className={styles.logo}></div>
                    <input
                        type="text"
                        className={styles.oInput}
                        name="username"
                        id="uname"
                        ref="uname"
                        placeholder="用户名/手机号/邮箱"
                        onChange={this.changeUsername}/>
                    <input
                        type="password"
                        className={styles.oInput}
                        name="password"
                        id="upwd"
                        ref="upwd"
                        placeholder="请输入您的密码"
                        onChange={this.changePassword}/>
                    <div className={styles.rememberPwd}>
                        {/*<input type="checkbox"  id="chk" className={styles.checkbox} checked={this.state.isRemember} onClick={this.handleCheckbox.bind(this)} />*/}
                        {/*<label className={styles.cbTxt} htmlFor="chk">记住账号</label>*/}
                        <span className={styles.forgetPwd}>忘记密码？</span>
                    </div>
                    <input
                        type="button"
                        className={styles.loginBtn}
                        value={this.state.loginLoading}
                        onClick={this.handleClick}/>
                    <p className={styles.p}>Copyright ©2018 Powered By PengHai</p>
                    <p className={styles.p}>Version 1.0.0</p>
                </form>
                <Modal
                    isOpen={this.state.modalIsOpen}
                    onAfterOpen={this.afterOpenModal}
                    onRequestClose={this.closeModal}
                    style={modelStyles}
                    contentLabel="LoginModal">

                    <h2 ref="subtitle">{modalMessage}</h2>
                    <button type='submit' style={modalBtnStyle} onClick={this.closeModal}>关闭</button>
                </Modal>
            </div>
        );
    }
};
